import { createLogger, format, transports } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

const { combine, timestamp, printf } = format;

// 自定义时间戳格式，使用本地时间
const localTimestamp = format((info, opts) => {
	info.timestamp = new Date().toLocaleString('zh-CN', { hour12: false });
	return info;
});

// 自定义格式，处理换行
const customFormat = printf(({ level, message, timestamp, ...metadata }) => {
	const formattedMessage = message.replace(/\n/g, '\n  '); // 为每个换行添加缩进
	return `${timestamp} [${level}]: ${formattedMessage}\n${JSON.stringify(metadata)}`;
});

// 创建一个通用的 DailyRotateFile 配置
const createRotateFileTransport = (filename: string, level?: string) => new DailyRotateFile({
	filename,
	datePattern: 'YYYY-MM-DD',
	zippedArchive: true,
	maxSize: '20m',  // 单个文件最大 20MB
	maxFiles: '14d', // 保留 14 天的日志
	level,
});

const winstonLogger = createLogger({
	format: combine(
		localTimestamp(),
		customFormat
	),
	defaultMeta: { service: 'log-service' },
	transports: [
		createRotateFileTransport('logs/errors/error-%DATE%.log', 'error'),
		createRotateFileTransport('logs/warnings/warning-%DATE%.log', 'warn'),
		createRotateFileTransport('logs/app/app-%DATE%.log'),
	],
});

export default winstonLogger;
